<template>
  <div class="registered-box">
    <div class="registered-info-box">
      <div class="steps-box">
        <div :class="{'active':isModuleNum == 1,'actived':isModuleNum > 1}">
          1.手机验证
        </div>
        <div :class="{'active':isModuleNum == 2,'actived':isModuleNum > 2}">
          2.实名信息补充
        </div>
        <div :class="{'active':isModuleNum == 3,'actived':isModuleNum > 3}">
          3.注册成功
        </div>
      </div>
      <div class="content-box">
        <div v-if="isModuleNum == 1">
          <h1 style="font-size:18px">注册账号</h1>
          <el-form ref="registeredFormRef" style="margin-top:20px" :model="registeredForm" :rules="registeredRules">
            <el-row>
              <el-col :span="12">
                <el-form-item prop="shopName" style="width:80%" label="商户名称">
                  <el-input v-model="registeredForm.shopName" clearable placeholder="请输入商户名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="shopUserName" style="width:80%" label="商户联系人">
                  <el-input v-model="registeredForm.shopUserName" clearable placeholder="请输入商户联系人" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item prop="firstPassword" style="width:80%" label="设置密码">
                  <el-input v-model="registeredForm.firstPassword" show-password type="password" clearable placeholder="请输入密码" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="shopUserPhone" style="width:80%" label="联系电话">
                  <el-input v-model="registeredForm.shopUserPhone" maxlength="11" clearable placeholder="请输入联系电话" />
                  <el-button style="margin-left:10px" type="primary"
                    @click="getCode">{{ countdown ? countdown+'s后再试' : '获取验证码' }}</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item prop="secondPassword" style="width:80%" label="二次确认">
                  <el-input v-model="registeredForm.secondPassword" show-password clearable placeholder="请再次输入密码" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="code" style="width:80%" label="验证码">
                  <el-input class="append" v-model="registeredForm.code" maxlength="6" placeholder="请输入验证码"
                    @keypress.enter="nextStep" @input="codeChange" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item prop="isAgreed">
                  <el-checkbox style="margin-right:10px;" v-model="isAgreed"></el-checkbox>
                  <el-link type="primary" @click="toAgreement">同意平台使用规则</el-link>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div style="text-align:center">
            <div class="next-btn" style="margin:10px auto 10px auto" @click="nextStep">下一步</div>
          </div>
          <div class="registered">已有账号？<span @click="toLogin">去登录</span></div>
        </div>
        <div v-if="isModuleNum == 2">
          <h1 style="font-size:18px">实名信息补充</h1>
          <el-form ref="realFormRef" style="margin-top:20px" :model="realForm" :rules="realRules">
            <el-row>
              <el-col :span="12">
                <el-form-item prop="shopType" style="width:80%" label="商户类型">
                  <el-radio-group v-model="realForm.shopType">
                    <el-radio :label="2">企业</el-radio>
                    <el-radio :label="1">个人</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="realForm.shopType == 2">
                <el-form-item prop="companyName" style="width:80%" label="企业名称">
                  <el-input v-model="realForm.companyName" clearable placeholder="请输入企业名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-else>
                <el-form-item prop="legalManName" style="width:80%" label="个人姓名">
                  <el-input v-model="realForm.legalManName" clearable placeholder="请输入您的真实姓名" @input="realinfoChange" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="realForm.shopType == 2">
              <el-col :span="12">
                <el-form-item prop="legalManName" style="width:80%" label="企业法人/联系人姓名">
                  <el-input v-model="realForm.legalManName" clearable placeholder="请输入企业法人/联系人姓名" @input="realinfoChange" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="certificateNumber" style="width:80%" label="法人/联系人身份证号">
                  <el-input v-model="realForm.certificateNumber" clearable placeholder="请输入法人/联系人身份证号" @input="realinfoChange" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12" v-if="realForm.shopType == 1">
                <el-form-item prop="certificateNumber" style="width:80%" label="个人身份证号">
                  <el-input v-model="realForm.certificateNumber" clearable placeholder="请输入个人身份证号" @input="realinfoChange" />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="realForm.shopType == 2">
                <el-form-item prop="licenseUrl" style="width:80%" label="上传营业执照">
                  <img v-show="!realForm.licenseUrl" style="width:100px;cursor:pointer" src="@a/imgs/businesslicense.png" alt=""
                    @click="uploadImg">
                  <div class="upload-box" v-show="realForm.licenseUrl">
                    <img :src="realForm.licenseUrl" alt="">
                    <el-icon color="#ffffff" class="upload-close" @click="removeImg">
                      <Close />
                    </el-icon>
                  </div>
                  <input ref="uploadInputRef" style="display:none" type="file" accept="image/*" @change="uploadChange">
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="orderNo" style="width:80%" label="支付宝实名认证">
                  <el-button :disabled="realSignState == 4" type="primary"
                    @click="getQrCode">{{ realSignState == 0 ? '点击获取认证二维码' : realSignState == 4 ? '认证成功' : '认证失败，请重新认证'}}</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="f-box">
            <el-button @click="isModuleNum = 1">上一步</el-button>
            <div class="next-btn" @click="submitHandle">提交审核</div>
          </div>
        </div>
        <div v-if="isModuleNum == 3" class="successful-box">
          <div class="info-box">
            <div>
              <el-icon class="suss-icon" color="#ffffff" size="50">
                <Check />
              </el-icon>
            </div>
            <h1 style="font-size:24px">恭喜您，注册成功</h1>
            <div style="color:#c88d8d">
              <p>-登录手机号-</p>
              <p>{{ registeredForm.shopUserPhone }}</p>
            </div>
          </div>
          <div class="next-btn" style="margin:50px auto 10px auto" @click="beginToUse">开始使用</div>
        </div>
      </div>
    </div>
  </div>
  <real-dialog ref="realDialogRef" @realEnd="realEnd" />
</template>

<script>
import { onMounted, reactive, ref, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import realDialog from './components/realDialog.vue'
import { warningDeal, getStore, getUrlParam, getExplorerInfo } from '@/utils/utils'
import api from './api'
import axios from "axios"
import hexMD5 from "@/utils/md5.min.js"
export default {
  components: {
    realDialog
  },
  setup() {
    const router = useRouter()

    const registeredFormRef = ref(null)
    const realFormRef = ref(null)
    const uploadInputRef = ref(null)
    const realDialogRef = ref(null)

    const validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次确认密码'))
      }
      if (value != state.registeredForm.firstPassword) {
        callback(new Error('两次密码不相同'))
      }
      if (value === state.registeredForm.firstPassword) {
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (!state.isAgreed) {
        callback(new Error('请勾选同意平台使用规则'))
      } else {
        callback()
      }
    }
    const smsCodePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入验证码'))
      }
      if (!state.SMSCode || value.length < 6) {
        callback(new Error('请输入正确的验证码'))
      } else {
        callback()
      }
    }
    const orderNoPass = (rule, value, callback) => {
      if (!state.realForm.orderNo) {
        callback(new Error('请完成实名认证'))
      } else {
        callback()
      }
    }
    const imgUrlPass = (rule, value, callback) => {
      if (!state.realForm.licenseUrl) {
        callback(new Error('请上传营业执照'))
      } else {
        callback()
      }
    }

    const state = reactive({
      realing: false,
      realSignState: 0,
      fileForm: {},
      SMSCode: false,
      countTimer: null,
      isAgreed: false,
      countdown: null,
      isModuleNum: 1,
      supplierShopCode: null,
      registeredForm: {},
      realForm: {
        shopType: 2,
      },
      registeredRules: {
        shopName: [
          { required: true, message: '请输入商户名称', trigger: 'blur' },
        ],
        shopUserName: [
          { required: true, message: '请输入商户联系人名称', trigger: 'blur' },
        ],
        shopUserPhone: [
          { required: true, message: '请输入商户联系人手机号', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: '手机号码格式不正确', trigger: 'blur'
          }
        ],
        firstPassword: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9]{6,}$/, message: '请输入6位以上且只包含数字、字母的密码', trigger: 'blur'
          },
        ],
        secondPassword: [
          { required: true, validator: validatePass, trigger: 'blur' },
        ],
        code: [
          { required: true, validator: smsCodePass, trigger: 'blur' },
        ],
        isAgreed: [
          { required: true, validator: validatePass2, trigger: 'blur' },
        ]
      },
      realRules: {
        shopType: [
          { required: true, message: '请选择商户类型', trigger: 'blur' },
        ],
        companyName: [
          { required: true, message: '请输入企业名称', trigger: 'blur' },
        ],
        legalManName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
        ],
        certificateNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          {
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号不正确', trigger: 'blur'
          },
        ],
        licenseUrl: [
          { required: true, validator: imgUrlPass, trigger: 'blur' },
        ],
        orderNo: [
          { required: true, validator: orderNoPass, trigger: 'blur' },
        ],
      },
    })

    function nextStep() {
      registeredFormRef.value.validate((valid, fields) => {
        if (!valid) return
        state.isModuleNum = 2
      })
    }

    //验证验证码
    async function codeChange(e) {
      if (e.length == 6) {
        const obj = {
          phone: state.registeredForm.shopUserPhone,
          source: 3,
          verificationCode: state.registeredForm.code,
        }
        await api.checkSmsCode(obj).then(res => {
          if (res.code == '200') {
            state.SMSCode = true
          } else {
            state.registeredForm.code = null
            state.SMSCode = false
            warningDeal(res.msg)
          }
        }).catch(err => {
          state.registeredForm.code = null
          state.SMSCode = false
          console.log(err)
        })
        registeredFormRef.value.validateField('code')
      }
    }

    function submitHandle() {
      realFormRef.value.validate((valid, fields) => {
        if (!valid) return
        const obj = {
          supplierShopCode: state.supplierShopCode,
          ...state.registeredForm,
          ...state.realForm,
          firstPassword: hexMD5(state.registeredForm.firstPassword),
          secondPassword: hexMD5(state.registeredForm.secondPassword),
        }
        api.webShop(obj).then(res => {
          if (res.code == '200') {
            state.isModuleNum = 3
          } else {
            warningDeal(res.msg)
          }
        }).catch(err => {
          console.log(err)
        })
        //下一步
      })
    }


    function toLogin() {
      router.push({ path: '/' })
    }

    function getCode() {
      //获取验证码
      registeredFormRef.value.validateField('shopUserPhone', (valid, fields) => {
        if (valid) {
          const obj = {
            phone: state.registeredForm.shopUserPhone,
            source: 3,
            type: 1,
          }
          api.getSmsCode(obj).then(res => {
            if (res.code == '200') {
              startCountdown()
            } else {
              warningDeal(res.msg)
            }
          }).catch(err => {
            console.log(err)
          })
        }
      })
    }

    function startCountdown() {
      clearInterval(state.countTimer)
      state.countdown = 60
      state.countTimer = setInterval(() => {
        state.countdown--
        if (state.countdown <= 0) {
          state.countdown = null
          clearInterval(state.countTimer)
        }
      }, 1000);
    }

    function getQrCode() {
      //获取支付宝实名二维码
      realFormRef.value.validateField('legalManName', (valid, fields) => {
        realFormRef.value.validateField('certificateNumber', (validT, fieldsT) => {
          if (valid && validT) {
            alipayReal()
          }
        })
      })
    }

    function realEnd(data) {
      state.realSignState = data.signState
      if (data.signState == 4) {
        state.realForm.orderNo = data.orderNo
      }
    }

    //支付宝实名
    function alipayReal() {
      const obj = {
        idCardName: state.realForm.legalManName,
        idCardNum: state.realForm.certificateNumber,
        source: 3,
      }
      api.livingCheckWeb(obj).then(res => {
        if (res.code == '200') {
          realDialogRef.value.dialogShow(res.data)
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function uploadImg() {
      uploadInputRef.value.click()
    }

    async function uploadFile() {
      let path = null
      let param = new FormData()  // 创建form对象
      param.append('file', state.fileForm.file, state.fileForm.fileName)  // 通过append向form对象添加数据
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          token: '',
          Authorization: `'','','',3,20,''`,
          platformHeadType: 'ilinkPlatform',
        }
      }
      let url = '/ums/file/upload/img'
      if (PROCESS_ENV.ENVIRONMENT == 'Production') {
        url = '/coupon_h5' + url
      }
      await axios.post(url, param, config).then(res => {
        if (res.data.code == '200') {
          path = res.data.data.ossUrl
        } else {
          warningDeal(res.data.msg)
        }
      }).catch(err => {
        console.log(err)
      })
      state.realForm.licenseUrl = path
    }

    //上传文件
    async function uploadChange(e) {
      state.fileForm = {}
      state.fileForm.file = e.target.files[0]
      state.fileForm.fileName = e.target.files[0].name
      await uploadFile()
      uploadInputRef.value.value = ''
    }

    function removeImg() {
      state.fileForm = {}
      state.realForm.licenseUrl = null
    }

    //开始使用
    function beginToUse() {
      router.push({ path: '/' })
      // const myObj = {
      //   account: state.registeredForm.shopUserName,
      //   password: hexMD5(state.registeredForm.firstPassword),
      //   key: state.loginForm.key,
      //   code: state.loginForm.code,
      // }
      // api.companyLogin(myObj).then(res => {
      //   if (res.code == '200') {
      //     window.localStorage.setItem('USER_TOKEN', res.data.token)
      //     window.localStorage.setItem('USER_INFO', JSON.stringify(res.data))
      //     window.localStorage.setItem('USER_AUTHOR', JSON.stringify({ Authorization: `${res.data.userId},'',${getExplorerInfo()},3,20,''` }))
      //     router.push({ path: '/home' })
      //   } else {
      //     warningDeal(res.msg)
      //   }
      // }).catch(err => {
      //   console.log(err)
      // })
    }

    //获取地址栏参数
    function getUrlParams() {
      const geturl = window.location.href
      if (geturl.indexOf('?') == -1) return {}
      let getqyinfo = geturl.split('?')[1]
      let getqys = getqyinfo.split('&')
      let obj = {}
      for (let i = 0; i < getqys.length; i++) {
        let item = getqys[i].split('=')
        let key = item[0]
        let value = item[1]
        obj[key] = value
      }
      return obj
    }

    function realinfoChange(e) {
      if (state.realSignState == 4) {
        state.realSignState = 0
        state.realForm.orderNo = null
      }
    }

    function toAgreement() {
      const href = router.resolve({
        name: '用户协议',
        path: '/agreement'
      })
      window.open(href.href, '_blank')
    }

    onMounted(() => {
      state.supplierShopCode = getUrlParams('shopCode').shopCode || null
    })

    return {
      ...toRefs(state),
      registeredFormRef,
      realFormRef,
      uploadInputRef,
      realDialogRef,
      nextStep,
      toLogin,
      submitHandle,
      getQrCode,
      uploadImg,
      uploadChange,
      removeImg,
      getCode,
      codeChange,
      realEnd,
      beginToUse,
      realinfoChange,
      toAgreement,
    }
  }
}
</script>

<style lang="scss" scoped>
.registered-box {
  width: 100%;
  height: 100%;
  background-color: #336feb;
  display: flex;
  .registered-info-box {
    width: 60%;
    background-color: #ffffff;
    border-radius: 5px;
    margin: auto;
    overflow: hidden;
    box-sizing: border-box;
    .steps-box {
      width: 100%;
      display: flex;
      justify-content: space-around;
      border-bottom: 1px solid #aaaaaa;
      > div {
        text-align: center;
        width: 33.3333%;
        box-sizing: border-box;
        padding: 20px 0;
        cursor: pointer;
        font-weight: bold;
      }
      > .actived {
        color: #0081ff;
        border-bottom: 2px solid #1b63e9;
      }
      > .active {
        color: #0081ff;
        border-bottom: 2px solid;
        border-image: linear-gradient(
            to right,
            #1b63e9,
            rgba($color: #1b63e9, $alpha: 0)
          )
          1;
      }
    }
  }
  .content-box {
    box-sizing: border-box;
    padding: 20px 50px;
  }
}
.next-btn {
  width: 300px;
  text-align: center;
  background-color: #0081ff;
  border-radius: 3px;
  color: #ffffff;
  padding: 8px 0;
  font-size: 14px;
  cursor: pointer;
}
.registered {
  text-align: center;
  > span {
    color: #1b63e9;
    cursor: pointer;
  }
}
.upload-box {
  position: relative;
  > img {
    max-width: 150px;
    max-height: 80px;
  }
  .upload-close {
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
    background-color: rgba($color: #000000, $alpha: 0.5);
  }
}

.successful-box {
  text-align: center;
  .info-box {
    display: flex;
    flex-flow: column;
    justify-content: center;
    gap: 20px;
    .suss-icon {
      background-color: #52c41a;
      padding: 5px;
      border-radius: 50%;
    }
  }
}
.f-box {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
}
</style>